//
//  TextView+emoji.swift
//  01-表情键盘
//
//  Created by 陈伟 on 15/10/25.
//  Copyright © 2015年 陈伟. All rights reserved.
//

import UIKit

extension UITextView {
    var emoticonText: String {
        let attrText = attributedText
        var strM = String()
        
        attrText.enumerateAttributesInRange(NSRange(location: 0, length: attrText.length), options: []) { (dict, range , _) -> Void in
            //            print("-------")
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                //                print("tupian\(attachment.emoticonModel)")
                strM += attachment.emoticonModel?.chs ?? ""
            }else {
                let str = (attrText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }
    
    func insertEmoticon(em: EmoticonModel){
        
        if em.isEmpty == true {
            return
        }
        if em.isRemoved == true {
            deleteBackward()
            return
        }
        
        if em.emoji != nil {
            replaceRange(selectedTextRange!, withText: em.emoji!)
            return
        }
        
        insertImage(em)
        
        delegate?.textViewDidChange?(self)
    }
    
    func insertImage(em: EmoticonModel) {
        let attachment = EmoticonAttachment(em: em)
        attachment.image = UIImage(contentsOfFile: em.pngPath!)
        let lineHeight = font?.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: lineHeight!, height: lineHeight!)
        //        let imageText = NSAttributedString(attachment: attachment)
        
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        imageText.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
        
        let strM = NSMutableAttributedString(attributedString: attributedText)
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        let range = selectedRange
        attributedText = strM
        selectedRange = NSRange(location: range.location+1, length: 0)
    }
}
